<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline" :labelCol="{ style: 'width:80px' }">
        <a-row :gutter="48">
          <!-- <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="车间">
              <j-dict-select-tag
                type="list"
                v-model="queryParam.workshop"
                dictCode="data_workshop,workshop_name,workshop_id"
                placeholder="请选择车间"
              />
            </a-form-item>
          </a-col> -->
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="工区">
              <j-multi-select-tag v-model="queryParam.areas" :options="areaOptions" placeholder="请选择工区" />
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="采样属性">
              <j-dict-select-tag
                type="list"
                v-model="queryParam.property"
                dictCode="data_property where status = 1 and prop_type = '日报',prop_name,prop_no"
                placeholder="请选择属性名称"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="11" :md="12" :sm="24">
            <a-form-item label="采样范围">
              <a-range-picker v-model="queryParam.startEndDate" />
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="采样间隔">
              <a-input v-model="queryParam.distanceValue">
                <template #addonAfter>
                  <a-select v-model="queryParam.distanceUnit" style="width: 80px">
                    <a-select-option value="天">天</a-select-option>
                    <a-select-option value="时">时</a-select-option>
                    <!-- <a-select-option value="分">分</a-select-option> -->
                  </a-select>
                </template>
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="聚合方式">
              <a-select placeholder="请选择" default-value="平均值" v-model="queryParam.aggregation">
                <a-select-option value="平均值">平均值</a-select-option>
                <a-select-option value="方差">方差</a-select-option>
                <a-select-option value="均方根">均方根</a-select-option>
                <a-select-option value="偏度">偏度</a-select-option>
                <a-select-option value="峭度">峭度</a-select-option>
                <a-select-option value="波形因子">波形因子</a-select-option>
                <a-select-option value="峰值因子">峰值因子</a-select-option>
                <a-select-option value="脉冲因子">脉冲因子</a-select-option>
                <a-select-option value="裕度因子">裕度因子</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col :md="6" :sm="24">
            <span
              class="table-page-search-submitButtons"
              :style="(advanced && { float: 'right', overflow: 'hidden' }) || {}"
            >
              <a-button type="primary" @click="handleSearch">查询</a-button>
              <a-button style="margin-left: 8px" @click="resetSearchForm">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <a-spin :spinning="loading">
      <a-tabs defaultActiveKey="1">
        <!-- 柱状图 -->
        <a-tab-pane tab="图表" key="1">
          <!-- <bar title="" :dataSource="barData" :height="height" /> -->
          <!-- <transfer-bar title="年度消耗流量一览表" :data="barData" x="日期" y="电压(V)" :height="height"/> -->
          <line-chart-multid :key="new Date().getTime()" :dataSource="lineData" :fields="fields" :height="height" />
          <!-- <bar-multid title="多列柱状图" :dataSource="lineData" :fields="fields" :height="height"/> -->
        </a-tab-pane>
        <!-- 多列柱状图 -->
        <a-tab-pane tab="数据" key="2">
          <a-table ref="table" size="default" :columns="columns" :data-source="barData2" />
        </a-tab-pane>
      </a-tabs>
    </a-spin>
  </a-card>
</template>

<script>
import Bar from '@/components/chart/Bar'
import BarMultid from '@/components/chart/BarMultid'
import LineChartMultid from '@/components/chart/LineChartMultid'
import TransferBar from '@/components/chart/TransferBar'
import STable from '@/components/table/'
import ATextarea from 'ant-design-vue/es/input/TextArea'
import AInput from 'ant-design-vue/es/input/Input'
import moment from 'moment'
import axios from 'axios'
import { httpAction, getAction } from '@/api/manage'
import JMultiSelectTag from '@/components/dict/JMultiSelectTag'

export default {
  name: 'TableList',
  components: {
    Bar,
    BarMultid,
    LineChartMultid,
    TransferBar,
    AInput,
    ATextarea,
    STable,
    JMultiSelectTag,
  },
  data() {
    return {
      height: document.body.clientHeight - 357,
      areaOptions: [{
          label:"选项一",
          value:"1"
        },{
          label:"选项二",
          value:"2"
        },{
          label:"选项三",
          value:"3"
        }],
      //barData: [],
      barData2: [],
      lineData: [],
      fields: ['电压'],
      dataList: [],
      visibleCreateModal: false,
      visible: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
      },
      form: null,
      mdl: {},

      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {
        workshop: 0,
        areas: '',
        property: '', //采样属性
        startDate: '', //
        endDate: '', //
        distanceValue: '', //采样间隔
        distanceUnit: '天', //采样间隔单位
        aggregation: '', //聚合方式
      },
      // 表头
      columns: [
        {
          title: '时间',
          dataIndex: 'date',
          width: '200px',
        },
        {
          title: '工区',
          dataIndex: 'area_name',
          needTotal: true,
          customRender: (text) => text,
        },
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {},
      loading: false,
      selectedRowKeys: [],
      selectedRows: [],
    }
  },
  created() {
    this.loadArea()
    this.resetSearchForm()
  },
  mounted() {
    const that = this
    window.onresize = () => {
      return (() => {
        that.height = document.body.clientHeight - 357
      })()
    }
  },
  methods: {
    handleSearch() {
      console.log('queryParam:', this.queryParam)
      var that = this
      if (!that.queryParam.areas) {
        this.$message.warning('请选择工区')
        return
      }
      if (!that.queryParam.property) {
        this.$message.warning('请选择采样属性')
        return
      }
      this.loadBarData()
    },
    loadData2(x, y, max, min, before = '', after = '') {
      let data = []
      for (let i = 0; i < 12; i += 1) {
        data.push({
          [x]: `${before}${i + 1}${after}`,
          [y]: Math.floor(Math.random() * max) + min,
        })
      }
      return data
    },
    // 加载柱状图数据
    loadBarData() {
      var that = this
      if (that.queryParam.startEndDate) {
        that.queryParam.startDate = moment(that.queryParam.startEndDate[0]).format('YYYY-MM-DD')
        that.queryParam.endDate = moment(that.queryParam.startEndDate[1]).format('YYYY-MM-DD')
      }
      var param = Object.assign({}, that.queryParam)
      that.loading = true
      httpAction('/external/hadoop/resample/areas', param, 'post')
        .then((res) => {
          if (res.success) {
            if (res.result && res.result.length == 0) {
              this.$message.warning('没有找到符合条件的数据')
              return
            }
            var list = []
            that.barData2 = []
            that.lineData = []
            var data = res.result
            that.barData2 = data
            that.dataList = data
            that.fields = that.getFields()
            that.setColumns()
            that.dataList.forEach((e) => {
              var lineObj = that.lineData.find((o) => o.type == e.date)
              if (!lineObj) {
                var obj = { type: e.date }
                for (let i = 0; i < that.fields.length; i++) {
                  const objKey = that.fields[i]
                  obj[objKey] = that.getValue(objKey, e.date)
                }
                that.lineData.push(obj)
              }
            })
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          that.loading = false
        })

      // this.barData = this.loadData2('x', 'y', 1000, 200)
    },
    loadArea() { 
      var that = this
      that.areaOptions = []
      
      var urlList = '/dataArea/dataArea/list'
      getAction(urlList)
        .then((res) => {
          if (res.success) {
            res.result.records.forEach((e) => {
              that.areaOptions.push({ 
                label: e.areaName,
                value: e.areaId.toString(),
              })
            })
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          that.loading = false
        })
    },
    setColumns() {
      var that = this
      that.columns = [
        {
          title: '时间',
          dataIndex: 'date',
          width: '200px',
        },
        {
          title: '工区',
          dataIndex: 'area_name',
          needTotal: true,
          customRender: (text) => text,
        },
      ]
      this.columns.push({
        title: '值',
        dataIndex: that.queryParam.property,
        needTotal: true,
        customRender: (text) => text,
      })
    },
    getValue(objKey, date) {
      var that = this
      var obj = that.dataList.find((item) => item.date == date && item.area_name == objKey)
      if (obj) {
        return parseFloat(obj[that.queryParam.property].toFixed(2))
      }
      return 0
    },
    getFields() {
      var that = this
      var areaNameList = []
      var date = that.dataList[0]['date']
      var list = that.dataList.filter((obj) => obj.date == date)
      for (let i = 0; i < list.length; i++) {
        const e = list[i]
        areaNameList.push(e['area_name'])
      }
      return areaNameList
    },
    handleEdit(record) {
      this.mdl = Object.assign({}, record)
      console.log(this.mdl)
      this.visible = true
    },
    handleOk() {},

    //添加逻辑
    handleModalVisible(isVisible) {
      this.visibleCreateModal = isVisible
    },
    handleCreateModalOk() {
      this.createForm.validateFields((err, fieldsValue) => {
        if (err) {
          return
        }
        const description = this.createForm.getFieldValue('description')
        axios
          .post('/saveRule', {
            desc: description,
          })
          .then((res) => {
            this.createForm.resetFields()
            this.visibleCreateModal = false
            this.loadRuleData()
          })
      })
    },
    handleCreateModalCancel() {
      this.visibleCreateModal = false
    },

    onChange(row) {
      this.selectedRowKeys = row.selectedRowKeys
      this.selectedRows = row.selectedRows

      console.log(this.$refs.table)
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    resetSearchForm() {
      var that = this
      that.queryParam = {
        // areas:'',
        workshop: 0,
        //property: '', //采样属性
        startDate: moment(new Date()).format('YYYY-MM') + '-01', //
        endDate: moment(new Date()).format('YYYY-MM-DD'), //
        distanceValue: '1',
        distanceUnit: '天',
        aggregation: '平均值',
      }
      // Object.assign(that.queryParam, { formValue: values })

      this.$set(that.queryParam, 'startEndDate', [that.queryParam.startDate, that.queryParam.endDate])
    },
  },
  watch: {
    /*
      'selectedRows': function (selectedRows) {
        this.needTotalList = this.needTotalList.map(item => {
          return {
            ...item,
            total: selectedRows.reduce( (sum, val) => {
              return sum + val[item.dataIndex]
            }, 0)
          }
        })
      }
      */
  },
}
</script>